<?php
declare(strict_types=1);

namespace app\appointment\controller;

use app\api\model\Setting as SettingModel;
use app\api\model\UploadFile as UploadFileModel;
use app\appointment\model\AppointmentForm as AppointmentFormModel;
use app\appointment\model\AppointmentSetting as AppointmentSettingModel;
use app\appointment\service\passport\Login as LoginService;
use app\common\enum\file\FileType as FileTypeEnum;
use app\common\enum\FormStatus as FormStatusEnum;
use app\appointment\service\Appointment as AppointmentService;
use app\appointment\model\Employee as EmployeeModel;
use app\common\enum\Setting as SettingEnum;
use app\common\library\storage\Driver as StorageDriver;


class Appointment extends Controller
{
    // 当前商城的上传设置
    private  $config;
    public function submit()
    {
        $user = $this->getLoginUser(false);
        $formData = $this->postForm();
        $returnData = ['isLogin' => false];
        if (!$user) {
            // 若用户不存在，则创建用户
            $LoginService = new LoginService();
            $userId = $LoginService->loginMpWx([
                'name' => $formData['name'],
                'phone' => $formData['phone'],
                'partyData' => [
                    'code' => $formData['code'],
                    'oauth' => 'MP-WEIXIN',
                ],
            ]);
            if (empty($userId)) {
                return $this->renderError($LoginService->getError());
            }

            // 获取登录成功后的用户信息
            $userInfo = $LoginService->getUserInfo();
            $returnData = array_merge($returnData, [
              'isLogin' => true,
              'userId' => (int)$userInfo['user_id'],
              'token' => $LoginService->getToken((int)$userInfo['user_id'])
            ]);
        }else {
          $userId = $user->user_id;
        }

        $model = new AppointmentFormModel();
        if (!$model->add($userId, $formData)) {
            return $this->renderError($model->getError() ?: '更新失败');
        }



        return $this->renderSuccess($returnData, '提交成功');
    }

    public function edit(int $appointmentId)
    {
        $user = $this->getLoginUser(false);
        if(!$user) {
            return $this->renderError('修改失败，请重试');
        }
        $model = AppointmentFormModel::get($appointmentId);
        if(!$model->edit($this->postForm())) {
            return $this->renderError($model->getError() ?: '修改失败');
        }

        return $this->renderSuccess('修改成功');
    }

    public function list($code)
    {
        $user = $this->getLoginUser(false);
        $returnData = ['isLogin' => false];
        if (!$user) {
            // token不存在，查找用户openid
            $LoginService = new LoginService();
            $userId = $LoginService->autoLoginMpWx($code);

            $returnData = array_merge($returnData, [
                'isLogin' => true,
                'userId' => (int)$userId,
                'token' => $LoginService->getToken((int)$userId)
            ]);

            return $this->renderSuccess($returnData, '登录成功');
        }else {
            $userId = $user->user_id;
        }

        $model = new AppointmentFormModel();
        $list = $model->getList(['user_id' => $userId]);

        return $this->renderSuccess(compact('list'));
    }





    public function detail(int $appointmentId)
    {
        $user = $this->getLoginUser(false);
        if (!$user) {
            // token不存在，让用户跳回到首页重新登陆
            return $this->renderError();
        }

        $model = new AppointmentFormModel();
        $detail = $model->get($appointmentId, ['images']);
        return $this->renderSuccess(compact('detail'));
    }



    public function cancel(int $appointmentId)
    {
        $user = $this->getLoginUser(false);
        if (!$user) {
            // token不存在，让用户跳回到首页重新登陆
            return $this->renderError();
        }

        $model = AppointmentFormModel::get(['user_id' => $user['user_id'], 'appointment_id' => $appointmentId]);
        if(!$model->switchStatus(FormStatusEnum::CANCELLED)) {
            return $this->renderError($model->getError() ?: '取消失败');
        }

        return $this->renderSuccess('取消成功');
    }

    /**
     * 获取小程序码
     */
    public function code(int $appointmentId)
    {
        $service = new AppointmentService();
        $base64 = $service->getCode($appointmentId, 'pages/checkin/checkin');
        return $base64;
    }

    /**
     * 登记，核销小程序码
     */
    public function checkin(int $appointmentId, string $code)
    {
        // 验证用户身份，是否为后台绑定员工
        $user = $this->getLoginUser(false);
        if (!$user) {
            // token不存在，查找用户openid
            $LoginService = new LoginService();
            $userId = $LoginService->autoLoginMpWx($code);
        }else {
            $userId = $user->user_id;
        }

        $employee = EmployeeModel::get(['user_id' => $userId]);
        if(empty($employee)) {
            // 员工不存在
            return $this->renderError('您还不是员工，请先绑定成为员工');
        }

        $appointment = AppointmentFormModel::get(['appointment_id' => $appointmentId]);
        if(!$appointment->checkin()) {
            return $this->renderError('签到失败，请重试');
        }

        return $this->renderSuccess('签到成功');
    }

    // 获取预约设置
    public function setting()
    {
        $setting = AppointmentSettingModel::get(['key' => 'appointment']);
        return $this->renderSuccess(compact('setting'));
    }

    /**
     * 构造方法
     * @throws \app\common\exception\BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function initialize()
    {
        parent::initialize();
        // 存储配置信息
        $this->config = SettingModel::getItem(SettingEnum::STORAGE, 10001);
    }


    /**
     * 图片上传接口
     * @param int $groupId 分组ID
     * @return array
     * @throws \think\Exception
     */
    public function uploadImage()
    {
        // 验证用户身份
        $user = $this->getLoginUser(false);

        // 实例化存储驱动
        $storage = new StorageDriver($this->config);


        // 设置上传文件的信息
        $storage
            ->setUploadFile('photo')
            ->setRootDirName('store')
            ->setValidationScene('image')
            ->upload();
        // 执行文件上传
        if (!$storage->upload()) {
            dump($storage->getError());
            exit;
            return $this->renderError('图片上传失败 upload image faile：' . $storage->getError());
        }
        // 文件信息
        $fileInfo = $storage->getSaveFileInfo();

        // 添加文件库记录
        $model = new UploadFileModel();
        $model->add($fileInfo, FileTypeEnum::IMAGE, 1001);
        $fileId = $model->file_id;
        return $this->renderSuccess(compact('fileId'), '添加成功');
    }

    /**
     * 删除文件
     */
    public function deleteFile(array $fileIds)
    {
        $model = new UploadFileModel();
        if (!$model->setDelete($fileIds)) {
            return $this->renderError($model->getError() ?: '操作失败');
        }
        return $this->renderSuccess('操作成功');
    }

}
